// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/expression/vector_function.h>

namespace kumo::pollux::test {
template <typename T>
struct TestingAlwaysThrowsFunction {
  template <typename TResult, typename TInput>
  void call(TResult&, const TInput&) {
    POLLUX_USER_FAIL();
  }
};

template <typename T>
struct TestingThrowsAtOddFunction {
  void call(bool& out, const int64_t& input) {
    if (input % 2) {
      POLLUX_USER_FAIL();
    } else {
      out = 1;
    }
  }
};

// Throw a PolluxException if polluxException_ is true. Throw an std exception
// otherwise.
class TestingAlwaysThrowsVectorFunction : public exec::VectorFunction {
 public:
  static constexpr const char* kPolluxErrorMessage = "Pollux Exception: Expected";
  static constexpr const char* kStdErrorMessage = "Std Exception: Expected";

  explicit TestingAlwaysThrowsVectorFunction(bool polluxException)
      : polluxException_{polluxException} {}

  void apply(
      const SelectivityVector& rows,
      std::vector<VectorPtr>& /* args */,
      const TypePtr& /* outputType */,
      exec::EvalCtx& context,
      VectorPtr& /* result */) const override {
    if (polluxException_) {
      auto error =
          std::make_exception_ptr(std::invalid_argument(kPolluxErrorMessage));
      context.setErrors(rows, error);
      return;
    }
    throw std::invalid_argument(kStdErrorMessage);
  }

  static std::vector<std::shared_ptr<exec::FunctionSignature>> signatures() {
    return {exec::FunctionSignatureBuilder()
                .returnType("boolean")
                .argumentType("integer")
                .build()};
  }

 private:
  const bool polluxException_;
};

} // namespace kumo::pollux::test
